<?php

namespace app\admin\controller;


use app\admin\logic\VideoLogic;
use think\Request;
use think\Db;
use app\common\model\Cate;

class Video extends BaseAdmin
{
    public function listing()
    {
        return $this->fetch();
    }

    public function ajax()
    {
        $r = (new VideoLogic())->listing();
        return $r;
    }

    public function editsort()
    {
        $state = array();
        $id = $_POST['id'];
        $des = $_POST['des'];
        $res = Db::table('video')->where(array('id'=>$id))->update(array('sort'=>$des));
        if( $res ) {
            return 1;
        }else{
            return 2;
        }
    }


    /**
     * @param Request $request
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function create(Request $request)
    {
        if ($request->isPost()) {
            $data = $request->only(['title', 'click_url', 'view', 'sort', 'number', 'pid', 'type', 'image', 'video', 'desc','create_time']);
            $logic = new VideoLogic();
            if ($logic->create($data) === false) {
                return apiReturnFail($logic->getError());
            }
            return apiReturnSuc();
        } else {
            $preat = Cate::select()->toArray();
            $this->assign('preat', $preat);
            return $this->fetch();
        }
    }


    public function update(Request $request)
    {
        $logic = new VideoLogic();
        if ($request->isPost()) {
            $data = $request->only(['title', 'click_url', 'desc', 'view', 'sort', 'number', 'pid', 'type', 'image', 'video', 'id','create_time']);
            $data['create_time'] = strtotime($data['create_time']);
            $data['update_time'] = time();
            if ($logic->update($data) === false) {
                return apiReturnFail($logic->getError());
            }
            return apiReturnSuc();
        } else {
            $id = $this->_get('id');
            $r = $logic->update($id, 'get');
            $this->assign('info', $r);

            $preat = Db::table('cate')->select();
            //var_dump($preat);die;
            $this->assign('preat', $preat);
            return $this->fetch();
        }
    }


    public function delete($id)
    {
        $r = (new VideoLogic())->delete($id);
        return apiReturnSuc($r);
    }
}